﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;

namespace HeUtils
{
    public static class AES
    {
        public static string CBCEncrypt(string content, string aesKey, string aesIV)
        {

            byte[] byteKEY = Encoding.UTF8.GetBytes(aesKey);
            byte[] byteIV = Encoding.UTF8.GetBytes(aesIV);

            byte[] byteContnet = Encoding.UTF8.GetBytes(content);

            var _aes = new RijndaelManaged();
            _aes.Padding = PaddingMode.PKCS7;
            _aes.Mode = CipherMode.CBC;

            _aes.Key = byteKEY;
            _aes.IV = byteIV;

            var _crypto = _aes.CreateEncryptor(byteKEY, byteIV);
            byte[] decrypted = _crypto.TransformFinalBlock(
                byteContnet, 0, byteContnet.Length);

            _crypto.Dispose();

            return Convert.ToBase64String(decrypted);
        }

        public static byte[] CBCDecrypt(byte[] ciphertext, byte[] key, byte[] iv)
        {
            var _aes = new RijndaelManaged();
            _aes.Padding = PaddingMode.PKCS7;
            _aes.Mode = CipherMode.CBC;

            _aes.Key = key;
            _aes.IV = iv;

            var _crypto = _aes.CreateDecryptor(key, iv);
            byte[] decrypted = _crypto.TransformFinalBlock(
                ciphertext, 0, ciphertext.Length);

            _crypto.Dispose();

            return decrypted;
        }

        public static byte[] CBCDecrypt(string ciphertext, string key, string iv)
        {
            byte[] byteKEY = Encoding.UTF8.GetBytes(key);
            byte[] byteIV = Encoding.UTF8.GetBytes(iv);
            byte[] byteDecrypt = System.Convert.FromBase64String(ciphertext);
            return CBCDecrypt(byteDecrypt, byteKEY, byteIV);
        }

        public static string DataToString(byte[] data)
        {
            return Encoding.UTF8.GetString(data);
        }
    }
}
